<template>
  <div class="userPage">
    <border title="人员列表" :foldUpBtn="true" :close="false" w="300px" h="500px">
      <div style="position: relative;padding-top: 5px">
        <el-button type="primary" size="mini" @click="getGpsInfo" style="margin: 10px">显示所有用户位置</el-button>
        <el-dropdown style="position: absolute; right: 10px; top:40%; ">
          <el-link icon="icon-ym icon-ym-mpMenu" :underline="false" />
          <el-dropdown-menu slot="dropdown" >
            <el-dropdown-item @click.native="toggleTreeExpand(true)">展开全部</el-dropdown-item>
            <el-dropdown-item @click.native="toggleTreeExpand(false)">折叠全部</el-dropdown-item>
            <!--            <el-dropdown-item @click.native="handleTypeManage">分类管理</el-dropdown-item>-->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div style="padding: 10px;">
        <el-input v-model="filterText" style="border: 1px solid #6199FF;border-radius: 4px;">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <div style="margin-top: 10px;height: calc(100% - 155px);overflow-y: auto;overflow-x: hidden;padding-right: 10px;position: relative;">
        <el-tree
          :data="groupTreeData"
          :props="defaultProps"
          show-checkbox
          :filter-node-method="filterNode"
          @check="userCheck"
          :default-expand-all="expandsTree"
          ref="tree"
          :expand-on-click-node="false"
          node-key="id"
          v-if="refreshTree"
          @node-click="handleNodeClick"
          v-loading="treeLoading"
          style="height: 100%; overflow: visible;">
          <div slot-scope="{ node, data }" style="width: 100%;">
            <!-- 群组节点 -->
            <div v-if="!data.isUser" class="treeLeve1" @dblclick="handleGroupDoubleClick(data)">
              <div style="display:flex;flex-direction: row;align-items: center;">
                <i class="el-icon-folder" />
                {{ data.name }}
              </div>
              <div style="display:flex;flex-direction: row;align-items: center;">
                <span style="color: #00afff;">{{ data.onlineCount || 0 }}</span>/<span>{{ data.userCount || 0 }}</span>
              </div>
            </div>
            <!-- 用户节点 -->
            <div v-else style="display:flex;flex-direction: row;align-items: center;justify-content: space-between;width: 100%;">
              <div style="display:flex;flex-direction: row;align-items: center;">
                <i class="el-icon-user" />
                <span style="margin-left: 10px;">{{ data.realName }}</span>
                <span style="margin-left: 10px;">{{ data.mobile }}</span>
              </div>
              <!-- 用户状态指示器 -->
              <div v-if="data.online" style="width: 8px;height: 8px;background: #67C23A;border-radius: 50%;margin-left: 10px;"></div>
              <div v-else style="width: 8px;height: 8px;background: #909399;border-radius: 50%;margin-left: 10px;"></div>
            </div>
          </div>
        </el-tree>
      </div>
    </border>

    <!--用户详情-->
    <userInfo ref="userInfoRes" :userInfo="userInfo"  :groupId="currentGroupId" @rtn="lszRtn" v-if="showInfo" @close="handleCloseTemporaryUser" />

    <!--群组-->
    <linshiPage
      @rtn="lszRtn"
      :userInfo="convertedData"
      :title="qzName"
      v-if="temporary"
      @close="handleCloseTemporary"
      @minimize="temporary = false"
      :qzAll="qzAll" />

    <!--即时通信-->
    <personMsgPage v-if="msgDiv" :msgData="msgData" :groupId="currentGroupId" @close="msgDiv = false" />
    <!--轨迹回放-->
    <trajectory @showMap="showMap" @time-range-selected="showMapToTime" :data="sharedData" v-if="trace"
                @play="(v) => $emit('play', v)" @close="trace = false" />

    <!--通知下发-->
    <noticePage v-if="noticeDiv" @close="noticeDiv = false" />
    <!--协同任务-->
    <collaboration v-if="collaDiv" :collaId="collaId" @close="collaDiv = false" />

    <collaborationGroup v-if="collaDivGroup" :collaIds="collaIds" @close="collaDivGroup = false" />
  </div>
</template>

<script>
import border from '../border/index.vue'
import personMsgPage from './models/personMsgPage.vue'
import userInfo from './models/userInfo.vue'
import linshiPage from "./models/linshiPage.vue";
import trajectory from './models/trajectory.vue'
import noticePage from './models/noticePage.vue'
import collaboration from './models/collaboration.vue'
import collaborationGroup from './models/collaborationGroup.vue'
import { getAll, getAllGpsInfo } from '@/api/gpsinfo'
import { getGroupTreeWithUsers } from '@/api/group' // 导入新的接口

export default {
  components: { border, personMsgPage, userInfo, linshiPage, trajectory, noticePage, collaboration,collaborationGroup },
  props: {
    allRoutes: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      refreshTree:true,
      expandsTree: false,
      drwz:undefined,
      currentGroupId: null, // 当前选中的群组ID
      msgData:undefined,
      collaDivGroup: false,
      collaId: undefined,
      collaIds: undefined,
      treeLoading: false,
      groupTreeData: [],
      convertedData: null,
      gpsInfoTimer: null,
      sharedData: "",
      filterText: '',
      showInfo: false,
      userInfo: {
        name: undefined
      },
      qzName: undefined,
      qzAll: [],
      temporary: false,
      msgDiv: false,
      trace: false,
      noticeDiv: false,
      collaDiv: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    filterText: {
      handler(val) {
        console.log('Filter text changed:', val);
        if (this.$refs.tree) {
          console.log('Calling tree filter method');
          this.$refs.tree.filter(val);
        } else {
          console.log('Tree ref not available');
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.initGroupTreeData()
    this.gpsInfoTimer = setInterval(() => {
      this.getGpsInfos()
    }, 5000)
  },
  beforeDestroy() {
    if (this.gpsInfoTimer) {
      clearInterval(this.gpsInfoTimer)
      this.gpsInfoTimer = null
    }
  },
  methods: {
    // 初始化群组树数据
    async initGroupTreeData() {
      this.treeLoading = true
      try {
        const response = await getGroupTreeWithUsers()
        if (response.code === 200) {
          // 转换数据结构，将用户列表转换为树节点
          this.groupTreeData = this.convertGroupTreeToNodes(response.data)
          console.log('群组树数据加载完成:', this.groupTreeData)
        } else {
          this.$message.error(response.msg || '获取群组数据失败')
        }
      } catch (error) {
        console.error('获取群组树失败:', error)
        this.$message.error('获取群组数据失败')
      } finally {
        this.treeLoading = false
        if (this.filterText) {
          this.$nextTick(() => {
            this.$refs.tree && this.$refs.tree.filter(this.filterText);
          });
        }
      }
    },
    // 切换树展开状态
    toggleTreeExpand(expands) {
      this.filterText = ''
      this.refreshTree = false
      this.expandsTree = expands
      this.$nextTick(() => {
        this.refreshTree = true
      })
    },
    handleCloseTemporary() {
      this.collaDivGroup = false
      this.msgDiv = false
      this.temporary = false;
      this.currentGroupId = null;
      this.qzAll = [];
      // 清除所有勾选状态
      this.$refs.tree.setCheckedKeys([]);
    },
    handleCloseTemporaryUser(){
      this.showInfo = false;
      this.msgDiv = false
      this.trace = false
      this.collaDiv = false
    },
    mapSetUser(arr){
      this.qzName = '临时群组';

      console.log('mapSetUser 收到数据:', arr);

      if (arr && arr.length > 0) {
        // 从传入的数据中提取用户ID（去重）
        const userIds = [...new Set(arr.map(item => item.id))];

        console.log('去重后的用户ID:', userIds);

        // 构建要勾选的节点key数组（用户节点的格式是 "user-用户ID"）
        const checkedKeys = userIds.map(userId => `user-${userId}`);

        console.log('要勾选的节点keys:', checkedKeys);

        // 设置勾选状态
        this.$refs.tree.setCheckedKeys(checkedKeys);

        // 获取选中的用户节点
        const selectedUserNodes = this.getSelectedUserNodes({
          checkedKeys: checkedKeys,
          halfCheckedKeys: []
        });

        console.log('选中的用户节点:', selectedUserNodes);

        // 去重后的用户节点
        const uniqueUserNodes = this.removeDuplicateUsers(selectedUserNodes);
        this.qzAll = uniqueUserNodes;

        console.log('最终用户列表:', uniqueUserNodes);

        // 获取这些用户的GPS信息并显示
        this.getSelectedUsersGpsInfo(uniqueUserNodes);

        this.temporary = true;
        this.$emit('mapSetUser', 'clear')
      } else {
        this.qzAll = [];
        this.temporary = false;
        this.currentGroupId = null;
        // 如果没有数据，清空勾选
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    getSelectedUsersGpsInfo(userNodes) {
      if (!userNodes || userNodes.length === 0) return;

      const startTime = 1759891187000;
      const endTime = new Date().getTime();
      const userIds = userNodes.map(node => node.account);

      console.log('获取GPS信息的用户IDs:', userIds);

      getAllGpsInfo(userIds, startTime, endTime).then(res => {
        console.log('GPS信息响应:', res);
        if (res.data && res.data.length > 0) {
          this.convertData(res.data);
        } else {
          console.log('没有获取到GPS数据');
          this.convertedData = null;
        }
      }).catch(error => {
        console.log('获取GPS信息失败:', error);
        this.convertedData = null;
      });
    },
    // 将分组树转换为树节点格式
    convertGroupTreeToNodes(groups) {
      if (!groups || !Array.isArray(groups)) return []

      return groups.map(group => {
        console.log('正在转换:', group)
        const node = {
          id: group.id,
          name: group.name,
          isUser: false,
          userCount: group.userCount || 0,
          onlineCount: group.onlineCount || 0,
          children: []
        }

        // 添加子分组
        if (group.children && group.children.length > 0) {
          node.children = node.children.concat(this.convertGroupTreeToNodes(group.children))
        }

        // 添加用户
        if (group.users && group.users.length > 0) {
          const userNodes = group.users.map(user => ({
            id: `user-${user.id}`,
            userId: user.id,
            realName: user.realName,
            account: user.account,
            mobile: user.mobile,
            online: user.online,
            isUser: true,
            headIcon: user.headIcon,
            department: user.department,
            position: user.position,
            lastReportTime: user.lastReportTime,
            groupId: group.id // 将群组ID添加到用户节点中
          }))
          node.children = node.children.concat(userNodes)
        }

        return node
      })
    },

    // 其他方法保持不变
    showMap(data,tableData) {
      this.$emit('showMap', data,tableData)
    },
    showMapToTime(startTime, endTime, data) {
      this.$emit('time-range-selected', startTime, endTime, data);
    },
    getGpsInfos() {
      getAll().then(res => {
        sessionStorage.setItem('tempGpsData', JSON.stringify(res.data))
        // const data = {
        //   "admin": {
        //     "userid": "admin",
        //     "type": 0,
        //     "lng": "114.20836441584699",
        //     "lat": "30.573999999512033",
        //     "distance": 14.2,
        //     "remark": "",
        //     "remark1": "湖北省武汉市汉阳区江汉二桥街道羿加同行教育",
        //     "remark2": "349057407209541",
        //     "time": 1761207250936,
        //     "tenantId": null,
        //     "status":"开机",
        //     "realName": "管理员"
        //   },
        //   "17786100896": {
        //     "userid": "17786100896",
        //     "type": 0,
        //     "lng": "114.243396",
        //     "lat": "30.517298",
        //     "distance": 1,
        //     "remark": "",
        //     "remark1": "湖北省武汉市汉阳区洲头街道丰巢",
        //     "remark2": "750719633442473285",
        //     "time": 1761211525148,
        //     "tenantId": null,
        //     "status":"开机",
        //     "realName": "刘小杰"
        //   }
        // }
        this.updateUserOnlineStatus(res.data);
      })
    },

    updateUserOnlineStatus(gpsData) {
      // 创建一个映射，用于快速查找用户在线状态
      // userid 对应 account，remark2 对应 userId
      const userStatusMap = {};

      // 遍历 gpsData 对象的所有键
      Object.keys(gpsData).forEach(key => {
        const user = gpsData[key];
        // userid 对应 account，remark2 对应 userId
        if (user.remark2) {
          userStatusMap[user.remark2] = user.status === "开机";
        }
      });

      // 递归遍历 groupTreeData 并更新用户在线状态
      const updateTreeData = (nodes) => {
        nodes.forEach(node => {
          if (node.isUser) {
            // 用户节点，根据 userId 更新在线状态
            node.online = userStatusMap[node.userId] || false;
          } else {
            // 群组节点，更新统计信息
            this.updateGroupOnlineCount(node);
            // 递归处理子节点
            if (node.children && node.children.length > 0) {
              updateTreeData(node.children);
            }
          }
        });
      };

      updateTreeData(this.groupTreeData);

      // 强制更新视图
      this.$forceUpdate();
    },

// 更新群组在线人数统计
    updateGroupOnlineCount(groupNode) {
      let onlineCount = 0;
      let userCount = 0;

      const countUsers = (nodes) => {
        nodes.forEach(node => {
          if (node.isUser) {
            userCount++;
            if (node.online) {
              onlineCount++;
            }
          } else if (node.children) {
            countUsers(node.children);
          }
        });
      };

      if (groupNode.children) {
        countUsers(groupNode.children);
      }

      // 更新群组统计信息
      groupNode.onlineCount = onlineCount;
      groupNode.userCount = userCount;
    },

    getGpsInfo() {
      getAll().then(res => {
        this.$emit('getGpsInfo', 'wz', res.data,this.drwz)
      }).catch(() => {})
    },
    userCheck(data, checked) {
      var startTime = 1759891187000;
      var endTime = new Date().getTime();

      console.log('勾选状态变化:', checked);

      const selectedUserNodes = this.getSelectedUserNodes(checked);
      this.showInfo = false
      // 如果没有选中任何用户，关闭临时群组
      if (selectedUserNodes.length === 0) {
        this.temporary = false;
        this.msgDiv = false
        this.collaDivGroup = false
        this.currentGroupId = null;
        this.qzAll = [];
        return;
      }

      console.log('选中的群组成员:', selectedUserNodes);

      // 去重：使用userId作为唯一标识
      const uniqueUserNodes = this.removeDuplicateUsers(selectedUserNodes);
      console.log('去重后的群组成员:', uniqueUserNodes);

      const userIds = uniqueUserNodes.map(node => node.account);

      getAllGpsInfo(userIds, startTime, endTime).then(res => {
        console.log('GPS数据:', res);
        this.convertData(res.data);
      }).catch(() => {
        console.log('获取GPS信息失败');
      });

      this.qzName = '临时群组';
      this.temporary = true;
      this.qzAll = uniqueUserNodes;
      console.log('临时群组成员:', this.qzAll);

      // 设置当前群组ID
      // if (uniqueUserNodes.length > 0 && uniqueUserNodes[0].groupId) {
      //   this.currentGroupId = uniqueUserNodes[0].groupId;
      // }
    },
    // 去重方法：根据userId去除重复的用户
    removeDuplicateUsers(userNodes) {
      const seen = new Set()
      return userNodes.filter(node => {
        // 使用userId作为唯一标识
        if (seen.has(node.userId)) {
          return false
        }
        seen.add(node.userId)
        return true
      })
    },
    getSelectedUserNodes(checkedInfo) {
      const userNodes = [];
      // 处理两种参数格式：对象或数组
      const checkedKeys = checkedInfo.checkedKeys || checkedInfo || [];

      console.log('处理的勾选keys:', checkedKeys);

      const traverse = (nodes) => {
        if (!nodes || !Array.isArray(nodes)) return;

        for (const node of nodes) {
          if (checkedKeys.includes(node.id)) {
            if (node.isUser) {
              userNodes.push(node);
            }
          }

          if (node.children) {
            traverse(node.children);
          }
        }
      };

      traverse(this.groupTreeData);
      return userNodes;
    },
    formatTime(timestamp) {
      // 如果时间戳是秒单位，转换为毫秒
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    convertData(data) {
      const grouped = {};

      data.forEach(item => {
        const { userid, lng, lat, time } = item;
        if (!grouped[userid]) {
          grouped[userid] = [];
        }
        grouped[userid].push({
          coord: [parseFloat(lng), parseFloat(lat)],
          time: this.formatTime(time)
        });
      });

      this.convertedData = Object.keys(grouped).map(userid => ({
        trackId: userid,
        points: grouped[userid]
      }));

      this.$emit('converted-data', this.convertedData);
      console.log('转换后的轨迹数据：', this.convertedData);
    },
    // filterNode(value, data) {
    //   if (!value) return true;
    //   if (data.isUser) {
    //     return data.realName.indexOf(value) !== -1 || data.mobile.indexOf(value) !== -1;
    //   } else {
    //     return data.name.indexOf(value) !== -1;
    //   }
    // },
    filterNode(value, data) {
      if (!value) return true;

      // 用户节点过滤
      if (data.isUser) {
        return data.realName.includes(value) || (data.mobile && data.mobile.includes(value));
      }
      // 群组节点过滤 - 需要检查群组名称和子节点
      else {
        // 如果群组名称匹配
        if (data.name.includes(value)) {
          return true;
        }
        // 检查子节点是否有匹配的
        const hasMatchingChild = (nodes) => {
          if (!nodes || !nodes.length) return false;

          for (const node of nodes) {
            if (node.isUser) {
              // 用户节点
              if (node.realName.includes(value) || (node.mobile && node.mobile.includes(value))) {
                return true;
              }
            } else {
              // 群组节点，递归检查
              if (node.name.includes(value) || hasMatchingChild(node.children)) {
                return true;
              }
            }
          }
          return false;
        };

        return hasMatchingChild(data.children);
      }
    },
    handleNodeClick(data, node) {

        console.log(data,'datadata')
        if (data.isUser) {
          this.showInfo = false
          this.$nextTick(() => {
            this.trace = false
            this.collaDiv = false
            this.handleCloseTemporary()
            this.userInfo = {
              name: data.realName,
              phone: data.account,
              online: data.online,
              userId: data.userId,
              headIcon: data.headIcon,
              department: data.department,
              position: data.position,
              lastReportTime: data.lastReportTime,
              groupId: data.groupId // 传递群组ID
            }
            // 设置当前群组ID
            // this.currentGroupId = data.groupId
            this.showInfo = true
          });
        }
    },
    handleGroupDoubleClick(data) {
      if (!data.isUser) {
        this.showInfo = false
        this.msgDiv = false
        this.collaDivGroup = false
        const allUsers = this.getAllUsersFromGroup(data);
        // 对双击群组的用户也进行去重
        const uniqueUsers = this.removeDuplicateUsers(allUsers);
        this.qzAll = uniqueUsers;
        console.log('去重后的群组用户:', this.qzAll);
        this.qzName = data.name;
        // 设置当前群组ID
        this.currentGroupId = data.id;

        // 自动勾选该群组的所有用户
        const checkedKeys = uniqueUsers.map(user => user.id);
        this.$refs.tree.setCheckedKeys(checkedKeys);

        // 获取这些用户的GPS信息
        this.getSelectedUsersGpsInfo(uniqueUsers);

        this.temporary = true;
      }
    },
    getAllUsersFromGroup(group) {
      let users = []

      const traverse = (node) => {
        if (node.children) {
          for (const child of node.children) {
            if (child.isUser) {
              users.push(child)
            } else {
              traverse(child)
            }
          }
        }
      }

      traverse(group)
      return users
    },
    lszRtn(v, txt) {
      switch (v) {
        case 'dw':
          this.$emit('rtn', 'dw', txt)
          break;
        case 'wz':
          this.$emit('rtn', 'wz', txt)
          console.log('wz', txt)
          break;
        case 'drwz':
          this.$emit('rtn', 'drwz', txt)
          this.drwz = txt
          break;
        case 'msgDiv':
          this.msgDiv = false
          this.trace = false;
          this.collaDiv = false
          this.collaDivGroup = false
          this.$nextTick(() => {
            this.msgDiv = true
            this.msgData = txt
            console.log(txt,'msgData')
          });
          break;
        case 'traje':
          this.trace = false;
          this.msgDiv = false
          this.collaDiv = false
          this.$nextTick(() => {
            this.sharedData = txt;
            this.trace = true;
            console.log("轨迹已选择", txt);
          });
          break;
        case 'notice':
          this.noticeDiv = true
          break;
        case 'colla':
          this.collaDiv = false
          this.trace = false;
          this.msgDiv = false
          this.$nextTick(() => {
            this.collaDiv = true
            console.log("colla", txt)
            this.collaId = txt
          });
          break;
        case 'collagroup':
          console.log(this.collaDivGroup)
          this.msgDiv = false
          this.collaDivGroup = true
          console.log("collagroup", txt)
          // this.collaIds = txt.map(item => item.userId)
          this.collaIds = txt
          console.log("collaIds", this.collaIds)
          console.log(this.collaDivGroup)

          break;
      }
    }
  }
}
</script>

<style scoped lang="scss">
.treeLeve1 {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  justify-content: space-between;
}
</style>
